import axios, { type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

/**
 * 智慧医疗管理系统 API 模块
 * 封装axios和接口调用方法
 */

// API响应接口定义
export interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// 分页响应接口
export interface PageResponse<T = any> {
  list: T[]
  total: number
  currentPage: number
  pageSize: number
}

// 创建axios实例 - 用于Read API
const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:5029/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 创建axios实例 - 用于Write API（增删改操作）
const writeApiClient = axios.create({
  baseURL: import.meta.env.VITE_API_WRITE_URL || 'http://localhost:5050/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - Read API
apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem('admin_token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 打印请求日志（开发环境）
    if (import.meta.env.DEV) {
      console.log('🚀 API Request:', config)
    }
    
    return config
  },
  (error) => {
    console.error('❌ Request Error:', error)
    return Promise.reject(error)
  }
)

// 请求拦截器 - Write API
writeApiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem('admin_token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 打印请求日志（开发环境）
    if (import.meta.env.DEV) {
      console.log('🚀 Write API Request:', config)
    }
    
    return config
  },
  (error) => {
    console.error('❌ Write API Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器 - Read API
apiClient.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    // 打印响应日志（开发环境）
    if (import.meta.env.DEV) {
      console.log('✅ API Response:', response)
    }
    
    const { data } = response
    
    // 统一处理业务错误
    if (data.code !== 200) {
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }
    
    return response
  },
  (error) => {
    console.error('❌ Response Error:', error)
    
    // 处理HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          localStorage.removeItem('admin_token')
          localStorage.removeItem('admin_userinfo')
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error('权限不足')
          break
        case 404:
          ElMessage.error('接口不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 响应拦截器 - Write API
writeApiClient.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    // 打印响应日志（开发环境）
    if (import.meta.env.DEV) {
      console.log('✅ Write API Response:', response)
    }
    
    const { data } = response
    
    // 统一处理业务错误
    if (data.code !== 200) {
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }
    
    return response
  },
  (error) => {
    console.error('❌ Write API Response Error:', error)
    
    // 处理HTTP错误状态码
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          localStorage.removeItem('admin_token')
          localStorage.removeItem('admin_userinfo')
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error('权限不足')
          break
        case 404:
          ElMessage.error('接口不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// ==================== 科室管理相关接口 ====================

export interface DepartmentItem {
  id?: number
  name: string
  level: string
  status: string
  description?: string
  doctorCount: number
  hospitalId: number
  parentId?: number
  uploader?: string
  uploadTime?: string
}

export interface DepartmentSearchParams {
  hospitalId: number
  name?: string
  level?: string
  status?: string
  currentPage?: number
  pageSize?: number
}

/**
 * 科室管理API
 */
export const departmentApi = {
  /**
   * 获取科室列表
   */
  getList(params: DepartmentSearchParams): Promise<ApiResponse<PageResponse<DepartmentItem>>> {
    return apiClient.get('/department', { params }).then(res => res.data)
  },
  
  /**
   * 获取科室详情
   */
  getDetail(id: number): Promise<ApiResponse<DepartmentItem>> {
    return apiClient.get(`/department/${id}`).then(res => res.data)
  },
  
  /**
   * 新增科室
   */
  add(data: DepartmentItem): Promise<ApiResponse<DepartmentItem>> {
    return writeApiClient.post('/department', data).then(res => res.data)
  },
  
  /**
   * 更新科室
   */
  update(data: DepartmentItem): Promise<ApiResponse<DepartmentItem>> {
    return writeApiClient.put(`/department/${data.id}`, data).then(res => res.data)
  },
  
  /**
   * 删除科室
   */
  delete(id: number): Promise<ApiResponse<null>> {
    return writeApiClient.delete(`/department/${id}`).then(res => res.data)
  },
  
  /**
   * 批量删除科室
   */
  batchDelete(ids: number[]): Promise<ApiResponse<null>> {
    return writeApiClient.delete('/department/batch', { data: { ids } }).then(res => res.data)
  }
}

// ==================== 医院管理相关接口 ====================

export interface HospitalItem {
  id?: number
  name: string
  imageUrl: string
  level: string
  type: string
  address: string
  phone: string
  description?: string
  isEnabled: boolean
  uploader?: string
  uploadTime?: string
}

export interface HospitalSearchParams {
  name?: string
  level?: string
  type?: string
  currentPage?: number
  pageSize?: number
}

/**
 * 医院管理API
 */
export const hospitalApi = {
  /**
   * 获取医院列表
   */
  getList(params: HospitalSearchParams): Promise<ApiResponse<PageResponse<HospitalItem>>> {
    return apiClient.get('/hospital', { params }).then(res => res.data)
  },
  
  /**
   * 获取医院详情
   */
  getDetail(id: number): Promise<ApiResponse<HospitalItem>> {
    return apiClient.get(`/hospital/${id}`).then(res => res.data)
  },
  
  /**
   * 新增医院
   */
  add(data: HospitalItem): Promise<ApiResponse<HospitalItem>> {
    return writeApiClient.post('/hospital', data).then(res => res.data)
  },
  
  /**
   * 更新医院
   */
  update(data: HospitalItem): Promise<ApiResponse<HospitalItem>> {
    return writeApiClient.put(`/hospital/${data.id}`, data).then(res => res.data)
  },
  
  /**
   * 删除医院
   */
  delete(id: number): Promise<ApiResponse<null>> {
    return writeApiClient.delete(`/hospital/${id}`).then(res => res.data)
  },
  
  /**
   * 批量删除医院
   */
  batchDelete(ids: number[]): Promise<ApiResponse<null>> {
    return writeApiClient.delete('/hospital/batch', { data: { ids } }).then(res => res.data)
  },
  
  /**
   * 上传医院图片
   */
  uploadImage(file: File): Promise<ApiResponse<{ url: string }>> {
    const formData = new FormData()
    formData.append('file', file)
    
    return writeApiClient.post('/fileupload/hospital/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => res.data)
  }
}

// ==================== 轮播图相关接口 ====================

export interface CarouselItem {
  id: number;  // 与后端int类型保持一致
  title: string;
  imageUrl: string;
  linkUrl?: string;
  status: number; // 0=Inactive, 1=Active
  statusName?: string;
  sort: number;
  uploader: string;
  uploadTime: string;
  createTime: string;
}

export interface CarouselSearchParams {
  title?: string
  startTime?: string
  endTime?: string
  currentPage?: number
  pageSize?: number
}

/**
 * 轮播图API
 */
export const carouselApi = {
  /**
   * 获取轮播图列表
   */
  getList(params: CarouselSearchParams): Promise<ApiResponse<PageResponse<CarouselItem>>> {
    return apiClient.get('/carousel', { params }).then(res => res.data)
  },
  
  /**
   * 获取轮播图详情
   */
  getDetail(id: number): Promise<ApiResponse<CarouselItem>> {
    return apiClient.get(`/carousel/${id}`).then(res => res.data)
  },
  
  /**
   * 新增轮播图
   */
  create(data: any): Promise<ApiResponse<CarouselItem>> {
    return writeApiClient.post('/carousel', data).then(res => res.data)
  },
  
  /**
   * 更新轮播图
   */
  update(id: number, data: any): Promise<ApiResponse<CarouselItem>> {
    // 构建符合后端CarouselUpdateDto要求的数据格式
    const updateData = {
      id: id,
      title: data.title,
      imageUrl: data.imageUrl,
      linkUrl: data.linkUrl || '',
      status: data.status, // 0=Inactive, 1=Active
      sort: data.sort || 1
    }
    return writeApiClient.put('/carousel', updateData).then(res => res.data)
  },
  
  /**
   * 删除轮播图
   */
  delete(id: number): Promise<ApiResponse<null>> {
    return writeApiClient.delete(`/carousel/${id}`).then(res => res.data)
  },
  
  /**
   * 批量删除轮播图
   */
  batchDelete(ids: number[]): Promise<ApiResponse<null>> {
    return writeApiClient.delete('/carousel/batch', { data: { ids } }).then(res => res.data)
  },
  
  /**
   * 上传轮播图图片
   */
  uploadImage(file: File): Promise<ApiResponse<{ url: string }>> {
    const formData = new FormData()
    formData.append('file', file)
    
    return writeApiClient.post('/fileupload/carousel/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(res => res.data)
  }
}

// ==================== 用户认证相关接口 ====================

export interface LoginParams {
  username: string
  password: string
}

export interface UserInfo {
  id: number
  username: string
  realName: string
  role: string
  avatar?: string
  permissions: string[]
}

/**
 * 认证API
 */
export const authApi = {
  /**
   * 用户登录
   */
  login(data: LoginParams): Promise<ApiResponse<{ token: string; userInfo: UserInfo }>> {
    return apiClient.post('/user/login', data).then(res => res.data)
  },
  
  /**
   * 用户登出
   * 注意：当前后端未实现登出接口，此接口可能返回404
   * 前端退出登录时建议直接使用本地清理方式
   */
  logout(): Promise<ApiResponse<null>> {
    return apiClient.post('/auth/logout').then(res => res.data)
  },
  
  /**
   * 获取用户信息
   */
  getUserInfo(): Promise<ApiResponse<UserInfo>> {
    return apiClient.get('/auth/userinfo').then(res => res.data)
  },
  
  /**
   * 刷新token
   */
  refreshToken(): Promise<ApiResponse<{ token: string }>> {
    return apiClient.post('/auth/refresh').then(res => res.data)
  }
}

// ==================== 通用工具方法 ====================

/**
 * 文件下载
 */
export const downloadFile = (url: string, filename?: string) => {
  const link = document.createElement('a')
  link.href = url
  if (filename) {
    link.download = filename
  }
  link.target = '_blank'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 * 图片预览
 */
export const previewImage = (url: string) => {
  window.open(url, '_blank')
}

// 默认导出API客户端
export default apiClient